import {
  GetModelList,
  PostModel,
  DeleteModel, GetPackageCourseList, SavePackageCourse, SavePackageUser, GetPackageUserList
} from "@/api/epackage";

import { GetSelectDicByCode } from '@/api/dictionary'
import { deepClone } from "@/utils";

const defaultModel = {
  Id: "",
  Name: "",
  Description: "",
  CoverUrl: "",
  ShowCoverUrl: "",
  CategoryId: "",
  TypeCode: "",
  Sort: "",
  FileId: "",
  DownloadUrl: "",
  Size: 0,
  OldPrice: 0,
  NowPrice: 0
};
export default {
  data() {
    return {
      viewModel: {
        PageIndex: 1,
        pageSize: 10,
        Name: '',
        CategoryId: '',
        TypeCode: ''
      },
      total: 0,
      dialogVisible: false,
      dialogType: "",
      model: Object.assign({}, defaultModel),
      modelList: [],
      apiPre: process.env.VUE_APP_BASE_API,
      actionUrl: "",
      loading: false,
      rules: {
        Name: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        CategoryId: [{ required: true, message: "请选择分类", trigger: "blur" }],
        ShowCoverUrl: [{ required: true, message: "请上传封面", trigger: "blur" }],
        TypeCode: [
          { required: true, message: "请选择基础分类", trigger: "blur" }
        ]
      },
      categoryList: [],
      queryCategoryList: [],
      typeList: [],
      queryTypeList: [],
      dialogVideoVisible: false,
      activeName: '1',
      activeUserName: '1',
      tabs: [
        {
          value: '1',
          label: '已关联'
        },
        {
          value: '0',
          label: '未关联'
        }
      ],
      videoViewModel: {
        PageIndex: 1,
        pageSize: 8,
        Name: '',
        Type: '1',
        PackageId: ''
      },
      videoList: [],
      videoTotal: 0,
      videoLoading: false,
      multipleSelection: [],
      chooseTags: [],
      guanlianModel: {
        CourseIdList: [],
        PackageId: ''
      },
      userViewModel: {
        PageIndex: 1,
        pageSize: 10,
        UserName: '',
        LoginName: '',
        Type: '1',
        PackageId: ''
      },
      userList: [],
      userTotal: 0,
      userLoading: false,
      dialogUserVisible: false,
      multipleUserSelection: [],
      guanlianUserModel: {
        UserIdList: [],
        PackageId: '',
        Type: 1
      }
    };
  },
  computed: {
    // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存
  },
  created() {
    // 实例创建完成后执行的代码
    this.GetModelList(this.viewModel);
    this.actionUrl = this.apiPre + "/Upload/UploadAttachment";
    this.GetDictionaryByPCode()
    this.setTypeList()
  },
  methods: {
    async GetDictionaryByPCode() {
      var res = await GetSelectDicByCode('YTJY');
      if (res && res.code == 200) {
        this.categoryList = res.data.Items
        this.queryCategoryList = deepClone(this.categoryList)
        this.queryCategoryList.unshift({
          id: '',
          value: '',
          label: '全部分类'
        })
      }
    },
    async setTypeList() {
      var res = await GetSelectDicByCode('banji');
      if (res && res.code == 200) {
        this.typeList = res.data.Items
        this.queryTypeList = deepClone(this.typeList)
        this.queryTypeList.unshift({
          value: '',
          label: '全部班级类型'
        })
      }
    },
    async GetModelList(viewModel) {
      this.loading = true
      const res = await GetModelList(viewModel);
      if (res.data) {
        this.total = res.data.TotalCount;
        this.modelList = res.data.Items;
      }

      this.loading = false
    },
    closeDialog() { },
    queryList() {
      this.viewModel.PageIndex = 1
      this.GetModelList(this.viewModel);
    },
    refresh() {
      this.viewModel.Name = ''
      this.viewModel.CategoryId = ''
      this.viewModel.TypeCode = ''
      this.viewModel.PageIndex = 1
      this.GetModelList(this.viewModel);
    },
    lastPage(val) {
      this.viewModel.page = val;
    },
    nextPage(val) {
      this.viewModel.page = val;
    },
    handleChange(value) {
      console.log(value);
    },
    handleSizeChange(val) {
      this.viewModel.pageSize = val;
      this.GetModelList(this.viewModel);
    },
    handleCurrentChange(val) {
      this.viewModel.page = val;
      this.GetModelList(this.viewModel);
    },
    handleAdd() {
      this.model = deepClone(defaultModel);
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示
      });
      this.dialogType = "new";
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.model = deepClone(row);
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示
        var fileIdElement = this.$refs.fileId
        var videourlElement = this.$refs.videourl
        var videoaddressElement = this.$refs.videoaddress
        fileIdElement.name = this.model.FileId
        videourlElement.name = this.model.DownloadUrl
        videoaddressElement.value = this.model.DownloadUrl

        console.log('fileIdElement.name', fileIdElement.name)
      });

    },
    async confirmModel() {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs["model"].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }

      var res = await PostModel(this.model);
      if (res && res.code == 200) {
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      } else {
        this.$notify({
          title: "失败",
          type: "error",
          message: res.message
        });
      }
      this.viewModel.page = 1;
      this.GetModelList(this.viewModel);
      this.model = deepClone(defaultModel);
      this.dialogVisible = false;
      this.$notify({
        title: "成功",
        type: "success",
        message: "操作成功!"
      });
    },
    handleDelete(row) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          var res = await DeleteModel(row.Id);
          if (res && res.code == 200) {
            this.$notify({
              title: "成功",
              type: "success",
              message: "操作成功!"
            });
          } else {
            this.$notify({
              title: "失败",
              type: "error",
              message: res.message
            });
          }
          this.GetModelList(this.viewModel);
        })
        .catch(err => {
          console.error(err);
        });
    },
    //图片上传成功回调
    handleAvatarSuccess(res, file) {
      //图片上传成功响应方法
      this.model.CoverUrl = res.data.SaveUrl
      this.model.ShowCoverUrl = res.data.DownloadUrl
      this.$notify({
        title: "成功",
        message: "上传完成!",
        type: "success",
        duration: 3000
      });
      this.loading = false
    },
    beforeAvatarUpload(file) {
      this.loading = true
      var fileName = file.name || ''
      var ext = fileName.split('.')[fileName.split('.').length - 1]

      const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
      // const isLt2M = file.size / 1024 / 1024 < 4;

      if (!isImg) {
        this.$notify({
          title: "失败",
          message: "上传图片只能是 JPG/JPEG/PNG 格式!",
          type: "error",
          duration: 3000
        });
        return false
      }
      return true
    },

    //课程关联视频
    handleClick(tab, event) {
      this.videoViewModel.Type = this.activeName
      this.queryVideoList()
    },
    async GetCourseVideoList() {
      this.videoLoading = true
      var res = await GetPackageCourseList(this.videoViewModel)
      if (res && res.code == 200) {
        this.videoList = res.data.Items
        this.videoTotal = res.data.TotalCount
      }
      this.videoLoading = false
    },
    guanlian(m) {
      this.dialogVideoVisible = true
      this.videoViewModel.PackageId = m.Id
      this.queryVideoList()
    },
    queryVideoList() {
      this.videoViewModel.PageIndex = 1
      this.GetCourseVideoList();
    },
    refreshVideo() {
      this.videoViewModel.Name = ''
      this.queryVideoList();
    },
    handleVideoSizeChange(val) {
      this.videoViewModel.pageSize = val;
      this.queryVideoList();
    },
    handleVideoCurrentChange(val) {
      this.videoViewModel.page = val;
      this.GetCourseVideoList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    cancelForm() {
      this.videoLoading = false;
      this.dialogVideoVisible = false
    },
    saveGuanlian() {
      if (this.videoLoading) {
        return;
      }
      this.videoLoading = true;

      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((it, index) => {
          this.chooseTags.push(it.Id)
        })
      }
      this.guanlianModel.Type = this.activeName
      this.guanlianModel.PackageId = this.videoViewModel.PackageId
      this.guanlianModel.CourseIdList = this.chooseTags

      SavePackageCourse(this.guanlianModel).then(response => {
        this.videoLoading = false;
        if (response.data) {
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            duration: 2000
          });
        } else {
          this.$notify({
            title: "错误",
            type: "error",
            message: response.message,
            duration: 5000
          });
        }
        this.multipleSelection = []
        this.chooseTags = []
        this.refreshVideo()
      }).catch(e => {
        this.videoLoading = false;
      });

      this.videoLoading = false
    },
    //套餐用户关联
    guanlianUser(m) {
      this.dialogUserVisible = true
      this.userViewModel.PackageId = m.Id
      this.activeUserName = '1'
      this.userViewModel.Type = this.activeUserName
      this.queryUserList()
    },
    async GetPackageUserList() {
      this.userLoading = true
      var res = await GetPackageUserList(this.userViewModel)
      if (res && res.code == 200) {
        this.userList = res.data.Items
        this.userTotal = res.data.TotalCount
      }
      this.userLoading = false
    },
    queryUserList() {
      this.userViewModel.PageIndex = 1
      this.GetPackageUserList();
    },
    refreshUser() {
      this.userViewModel.LoginName = ''
      this.userViewModel.UserName = ''
      this.GetPackageUserList();
    },
    handleUserSizeChange(val) {
      this.userViewModel.pageSize = val;
      this.queryUserList();
    },
    handleUserCurrentChange(val) {
      this.userViewModel.page = val;
      this.GetPackageUserList();
    },
    handleUserSelectionChange(val) {
      this.multipleUserSelection = val;
    },
    saveUserGuanlian() {
      if (this.userLoading) {
        return;
      }
      this.userLoading = true;

      var chooseId = []
      if (this.multipleUserSelection.length > 0) {
        this.multipleUserSelection.forEach((it, index) => {
          chooseId.push(it.UserID)
        })
      }
      this.guanlianUserModel.Type = this.activeUserName
      this.guanlianUserModel.PackageId = this.userViewModel.PackageId
      this.guanlianUserModel.UserIdList = chooseId

      SavePackageUser(this.guanlianUserModel).then(response => {
        this.userLoading = false;
        if (response.data) {
          this.$notify({
            title: "成功",
            message: "保存成功",
            type: "success",
            duration: 2000
          });
        } else {
          this.$notify({
            title: "错误",
            type: "error",
            message: response.message,
            duration: 5000
          });
        }
        this.multipleUserSelection = []
        chooseId = []
        this.refreshUser()
      }).catch(e => {
        this.userLoading = false;
      });

      this.userLoading = false
    },
    //课程关联视频
    handleUserClick(tab, event) {
      this.userViewModel.Type = this.activeUserName
      this.refreshUser()
    },
  }
}